<?php

class UserManager {

	private $db;

	function __construct() {
		global $db;

		$this->db = $db;

	}

	// Interface

	/**
	 * Return an associative array of existing users, indexed by ID
	 */ 
	public function getUsers() {

		$users = array();

		// Setup the query to fetch user data from the DB
		$query = $this->db->query("SELECT * FROM users");
	
		// Loop through raw data and convert to User objects
		while( $userdata = $query->fetch_assoc() ) {

			// Before: array( 'id' => 1, 'login' => 'grady', 'first_name' => 'Mike', ...)
			extract($userdata);
			// After: $id = 1, $login = 'grady', $first_name = 'Mike', ...

			// Create a new user object for this database row
			$user = new User( $id, $login, $first_name, $last_name, $email, $password );

			// Add it to our resulting user list, indexed by ID
			$users[$id] = $user;

		}

		return $users;

	}

	public function getUser( $id ) {

		// Setup the query to fetch user data from the DB
		$query = $this->db->query("SELECT * FROM users WHERE id = '$id'");
		
		$userdata = $query->fetch_assoc();

		// Check results
		if( empty( $userdata ) )
			return false;

		// Before: array( 'id' => 1, 'login' => 'grady', 'first_name' => 'Mike', ...)
		extract($userdata);
		// After: $id = 1, $login = 'grady', $first_name = 'Mike', ...

		// Create a new user object for this database row
		$user = new User( $id, $login, $first_name, $last_name, $email, $password );

		return $user;

	}

}

class User {

	private $id;
	private $login;
	private $first_name;
	private $last_name;
	private $password;
	private $email;

	/**
	 * Create a user object with the supplied parameters
	 */ 
	public function __construct( $id, $login, $first_name, $last_name, $email, $password ) {

		$this->id = $id;
		$this->login = $login;
		$this->first_name = $first_name;
		$this->last_name = $last_name;
		$this->email = $email;
		$this->password = $password;

	}

	// Interface
	public function sendEmail( $subject, $message ) {

		if( ! isset( $this->email ) )
			return false;

	}

	public function getEmailLink() {

		return sprintf( '<a href="mailto:%s">%s</a>', $this->email, $this->getFullName() );
		
	}

	public function getFullName() {

		return $this->first_name . ' ' . $this->last_name;

	}

	// Getters and Setters (accessor methods)

	public function getId() {
		
		return $this->id;
		
	}

	public function getLogin() {
		
		return $this->login;

	}

	public function getFirstName() {
		
		return $this->first_name;
		
	}

	public function getLastName() {
		
		return $this->last_name;
		
	}

	public function getEmail() {
		
		return $this->email;
		
	}

	public function getPassword() {

		return md5( $this->password );

	}

	public function setPassword( $newpassword ) {

		$this->password = $newpassword;

	}

}